package cn.wzvtc.common.dto;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.Serializable;

/**
 * @author Shiwei Xu
 * @date 2020/5/26
 */
@Getter
@Setter
public class Pagination implements Serializable {
  private static final Logger log = LoggerFactory.getLogger(Pagination.class);

  private static final long serialVersionUID = 1002L;

  /***
   * 当前页
   */
  private int page = 1;

  /***
   * 默认每页数量10
   */
  private int limit = 10;

  /**
   * 排序字段，默认id
   */
  private String orderField = "id";

  /**
   * 排序方式，可选值(asc、desc)
   */
  private String order = "desc";

  /**
   * 转换为IPage
   */
  public <T> IPage<T> toIPage(){
    Page<T> page = new Page<>(this.page, this.limit);
    if (!StringUtils.isEmpty(this.orderField) && !StringUtils.isEmpty(this.order)) {
      if ("asc".equalsIgnoreCase(this.order)) {
        page.addOrder(OrderItem.asc(this.orderField));
      } else {
        page.addOrder(OrderItem.desc(this.orderField));
      }
    }
    return page;
  }
}
